#include "addinfo.h"
#include "ui_addinfo.h"

AddInfo::AddInfo(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::AddInfo)
{
    ui->setupUi(this);
    this->setFixedSize(this->width (),this->height());//固定窗体
    this->setSignals();
    // QObject::connect(pushButton, SIGNAL(clicked()), AddInfo, SLOT(save()));
}

AddInfo::~AddInfo()
{
    delete ui;
}

void AddInfo::save(){
	QString name=ui->lineEdit->text();
	QString price=ui->lineEdit_2->text();
	QString thumb=ui->lineEdit_3->text();
	QString seller_id=ui->lineEdit_4->text();
	QString note=ui->lineEdit_5->text();
	//qDebug()<< seller_id;
	
	MySQLDBHelper dbHelper = MySQLDBHelper();
    QString sql;
    if(id==0){
        sql = "insert into dishes(dishes_name,price,thumb,seller_id,note) values ('"+name+"','"+price+"','"+thumb+"','"+seller_id+"','"+note+"')";
    }else{
        sql="update dishes set dishes_name='"+name+"',price='"+price+"',thumb='"+thumb+"',seller_id='"+seller_id+"',note='"+note+"' where id='"+QString::number(id)+"'";
    }    
    QSqlQuery query = dbHelper.getQuery();
    query.exec(sql);
    if(query.numRowsAffected()==0){
    	qDebug()<<query.lastError()<<sql;
    }
    emit sendMsg(0);
    this->close();
    this->reset();
}

// 置空所有输入控件
void AddInfo::reset(){
    ui->lineEdit->setText("");
    ui->lineEdit_2->setText("");
    ui->lineEdit_3->setText("");
    ui->lineEdit_4->setText("");
    ui->lineEdit_5->setText("");
}

void AddInfo::getInfo(int id){
    MySQLDBHelper dbHelper = MySQLDBHelper();
    QString sql="select dishes_name,price,thumb,seller_id,note from dishes where id='"+QString::number(id)+"'";
    // sql.append(QString::number(id));
    // sql.append("'");
//    qDebug()<<sql;
    QSqlQuery query = dbHelper.getQuery();
    query.exec(sql);
//    qDebug()<<query.size();
    if(query.next()){
        // qDebug()<<query.value(0).toString();
        // qDebug()<<query.value(1).toString();
        // qDebug()<<query.value(2).toString();
        // qDebug()<<query.value(3).toString();
        // qDebug()<<query.value(4).toString();
        ui->lineEdit->setText(query.value(0).toString());
        ui->lineEdit_2->setText(query.value(1).toString());
        ui->lineEdit_3->setText(query.value(2).toString());
        ui->lineEdit_4->setText(query.value(3).toString());
        ui->lineEdit_5->setText(query.value(4).toString());
    }
}

void AddInfo::setId(int id){
    this->id=id;
    // 当id>0时，即认为进入编辑模式，自动调取目标记录默认值
    if(id>0){
        this->getInfo(id);
    }
}

void AddInfo::setSignals(){
    QObject::connect(ui->pushButton,SIGNAL(clicked(bool)), this,SLOT(save()));
}

